// 网络工具类
const config = require('./config.js')

class NetworkUtils {
  
  // 测试服务器连接
  static testServerConnection() {
    return new Promise((resolve, reject) => {
      console.log('测试服务器连接:', config.serverUrl)
      
      wx.request({
        url: `${config.serverUrl}/api/boxes`,
        method: 'GET',
        timeout: 5000,
        enableHttp2: false,
        enableQuic: false,
        success: (res) => {
          console.log('服务器连接测试成功:', res)
          resolve({
            success: true,
            status: res.statusCode,
            data: res.data
          })
        },
        fail: (err) => {
          console.error('服务器连接测试失败:', err)
          reject({
            success: false,
            error: err,
            message: this.getErrorMessage(err)
          })
        }
      })
    })
  }
  
  // 获取错误信息
  static getErrorMessage(err) {
    if (err.errMsg) {
      if (err.errMsg.includes('timeout')) {
        return '请求超时，请检查网络连接'
      } else if (err.errMsg.includes('fail')) {
        return '连接失败，请检查服务器是否启动'
      } else if (err.errMsg.includes('abort')) {
        return '请求被中断'
      }
    }
    return '网络连接失败，请检查网络设置'
  }
  
  // 发送MQTT指令
  static sendMqttCommand(topic, message) {
    return new Promise((resolve, reject) => {
      console.log('发送MQTT指令:', { topic, message })
      
      wx.request({
        url: `${config.serverUrl}/api/mqtt/message/publish`,
        method: 'POST',
        header: {
          'content-type': 'application/json'
        },
        data: {
          topic: topic,
          message: message
        },
        timeout: config.requestTimeout,
        success: (res) => {
          console.log('MQTT指令发送成功:', res)
          if (res.statusCode === 200) {
            resolve(res.data)
          } else {
            reject(new Error(`HTTP ${res.statusCode}: ${res.data?.message || '发送失败'}`))
          }
        },
        fail: (err) => {
          console.error('MQTT指令发送失败:', err)
          reject(new Error(this.getErrorMessage(err)))
        }
      })
    })
  }
  
  // 更新柜子状态
  static updateCabinetStatus(cabinetId, status) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: `${config.serverUrl}/api/boxes/${cabinetId}/status`,
        method: 'POST',
        header: {
          'content-type': 'application/json'
        },
        data: {
          status: status
        },
        success: (res) => {
          if (res.statusCode === 200) {
            resolve(res.data)
          } else {
            reject(new Error(`更新状态失败: ${res.statusCode}`))
          }
        },
        fail: (err) => {
          reject(new Error(this.getErrorMessage(err)))
        }
      })
    })
  }
  
  // 网络诊断
  static async diagnoseNetwork() {
    const results = {
      serverReachable: false,
      apiWorking: false,
      mqttWorking: false,
      errors: []
    }
    
    try {
      // 测试基本连接
      const connectionTest = await this.testServerConnection()
      results.serverReachable = connectionTest.success
      results.apiWorking = connectionTest.success && connectionTest.status === 200
      
      // 测试MQTT功能
      if (results.apiWorking) {
        try {
          await this.sendMqttCommand('test/connection', { type: 'TEST', timestamp: Date.now() })
          results.mqttWorking = true
        } catch (mqttErr) {
          results.errors.push(`MQTT测试失败: ${mqttErr.message}`)
        }
      }
      
    } catch (err) {
      results.errors.push(`连接测试失败: ${err.message}`)
    }
    
    return results
  }
}

module.exports = NetworkUtils